package com.wago.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;

/**
 * Created by webrx on 2017-09-01.
 */
    public class MyHelper<E> {
        private SqlSessionFactory sf;
        private SqlSession ss;
        private Class e;
        public MyHelper(){
            InputStream i = null;
            try {
                i = Resources.getResourceAsStream("mybatis-conf.xml");
                this.sf = new SqlSessionFactoryBuilder().build(i);
                this.ss = this.sf.openSession();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public SqlSessionFactory getSqlSessionFactory(){
            return this.sf;
        }

        public Connection getConn(){
            return this.ss.getConnection();
        }

        public MyHelper(Class e){
            InputStream i = null;
            try {
                i = Resources.getResourceAsStream("mybatis-config.xml");
                this.sf = new SqlSessionFactoryBuilder().build(i);
                this.ss = this.sf.openSession();
                this.e = e;
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }


        public SqlSession getSession(){
            return this.ss;
        }

        public SqlSession getSessions() {
            return this.sf.openSession();
        }

        public E getMapper(){
            return (E)this.ss.getMapper(this.e);
        }

        public E getMapper(Class c){
            return (E)this.ss.getMapper(c);
        }



        public void close(){
            if(this.ss!=null){
                this.ss.commit();
                this.ss.close();
            }
        }
    }

